# -*- coding: utf-8 *-*

import pygeoip

from json import dumps

from mongoengine.django.auth import User 
from mongoengine.django.storage import GridFSStorage

from django.utils.encoding import smart_unicode

from account.utils import __make_avatar

from place.models import *
from place.forms import *

from forms import *
from models import People 

from utils import __make_uid
from utils import __make_tags_list
from utils import __make_img_thumb
from utils import __make_gridfs_images

from codename_bamboo.preference import ONE_LONGITUDE
from codename_bamboo.preference import DEFAULT_RADIUS
from codename_bamboo.preference import DEFAULT_QUERY_LENGTH    

from codename_bamboo.preference import GEOIP_CITY_DATABASE
geoip = pygeoip.GeoIP(GEOIP_CITY_DATABASE)                   


def _get_profile(username):
    """
    Return one people's profile
    """
    user = User.objects.get(username=username)
    people = People.objects.get(user=user)
    places = Place.objects.get(master=username)
    subjects = PlaceSubject.objects.get(username=username)

    avatar_id = str(people.avatar.grid_id)
    friends = people.friends

    profile = {'username': username
            ,'avatar_id': avatar_id
            ,'places': places
            ,'friends': friends
            ,'subjects': subjects
            }

    return profile


def _get_avatar_id(username):
    """
    Return gridfs id of people's avatar image
    """
    print(username)
    user = User.objects.get(username=username)
    people = People.objects.get(user=user)
    avatar_id = str(people.avatar.grid_id)

    if not avatar_id or avatar_id == 'None':
        return None
    else:
        return avatar_id                           


def _ensure_location(request, response, home_location=True, last_location=True):
    """
    Try ensure there are latitude and longitude data
    inside the people browser's cookie and django session storage
    """
    latitude = longitude = ''
    if home_location:
        if not 'homeLatitude' in request.session or not 'homeLongitude' in request.session:
            record    = geoip.record_by_addr('114.82.2.47') # request.META['REMOTE_ADDR'])
            latitude  = str(record['latitude'])
            longitude = str(record['longitude'])

            request.session['homeLatitude']  = latitude
            request.session['homeLongitude'] = longitude
        else:
            latitude = request.session['homeLatitude']
            longitude = request.session['homeLongitude']

        response.set_cookie('homeLatitude', latitude)
        response.set_cookie('homeLongitude', longitude)

    if last_location:
        if 'lastLatitude' in request.session and 'lastLongitude' in request.session:
            latitude  = request.session['lastLatitude']
            longitude = request.session['lastLongitude']

        response.set_cookie('lastLatitude', latitude)
        response.set_cookie('lastLongitude', longitude)

    # Need to retur something?
    return (request, response)


def _handle_preference_home(request):
    """
    Store people's new home latitude and longitude 
    into session database
    """
    if 'homeLatitude' in request.POST and 'homeLongitude' in request.POST:
        request.session['homeLatitude'] = request.POST['homeLatitude']
        request.session['homeLongitude'] = request.POST['homeLongitude']
        print(request.POST['homeLatitude'])
        print(request.POST['homeLongitude'])
        print(request.session['homeLatitude'])
        print(request.session['homeLongitude'])
        results = {'ok': True}
    else:
        results = {'ok': False}

    return dumps(results)


def _handle_preference_avatar(request):
    """
    Update people's avata 
    """
    print(request.FILES)
    form = PreferenceAvatarForm(request.POST, request.FILES)
    if not form.is_valid():
        print(request.FILES)
        print('form is not valid')
        return dumps({'ok':False})
    else:
        user = request.user
        password = user.password
        people = People.objects.get(user=user)
        raw_file = request.FILES['avatar']
        new_avatar = __make_avatar(raw_file, password)

        try:
            if not people.avatar.grid_id:
                people.avatar = new_avatar
            else:
                people.avatar.replace(new_avatar)
                print(people.avatar.grid_id)
            people.save()
        except Exception:
            print(Exception.args)
            #return dumps({'ok':False})
            return False
        else:
            #return dumps({'ok':True,'grid_id':people.avatar.grid_id});
            return True


def _handle_mark_place(request):
    """
    Store the place infomation that peole submitted
    """
    print(request.POST.encoding)
    print(request.POST)
    if request.FILES:
        form = PlaceForm(request.POST, request.FILES)
    else:
        form = PlaceForm(request.POST)

    if not form.is_valid():
        print('form is not valid')
        print(form)
        return False
    else:
        name = form.cleaned_data['name']
        username = request.user.username
        uid = __make_uid(name,form.cleaned_data['latitude'],form.cleaned_data['longitude'])
        country = form.cleaned_data['country']
        print(country)
        region = form.cleaned_data['region']
        city = form.cleaned_data['city']
        print(city)
        district = form.cleaned_data['district']
        address = form.cleaned_data['address']
        latitude = float(form.cleaned_data['latitude'])
        longitude = float(form.cleaned_data['longitude'])
        discover = smart_unicode(username)
        genre = form.cleaned_data['genre']
        description = form.cleaned_data['description']
        raw_tags = form.cleaned_data['tags']

        place = Place(uid=uid
                ,name=name
                ,country=country
                ,region=region
                ,city=city
                ,district=district
                ,address=address
                ,location=(latitude, longitude)
                ,discover=discover
                ,genre=genre
                ,description=description
                )

        if raw_tags:
            place.tags = __make_tags_list(raw_tags)

        if 'image' in request.FILES:
            raw_file = request.FILES['image']
            image, thumb = __make_gridfs_images(raw_file, uid, username)
            subject = PlaceSubject(username=username, image=image, thumb=thumb)
            subject.save()
            place.subjects.append(subject)

        try:
            place.save()
        except Exception:
            print(Exception.args)
            return False
        else:
            return uid


def _handle_place_comment(request, uid):
    """
    Store people's comment on a specific place
    into the database
    """
    print(request.FILES)
    if request.FILES:
        form = PlaceCommentForm(request.POST, request.FILES)
    else:
        form = PlaceCommentForm(request.POST)

    if not form.is_valid():
        print('form is not valid')
        print(form)
        return False
    else:
        username = request.user.username
        comment = form.cleaned_data['comment']

        place = Place.objects.get(uid=uid)
        place_comment = PlaceComment(username=username, comment=comment)


        if 'photo' in request.FILES:
            raw_file = request.FILES['photo']
            image, thumb = __make_gridfs_images(raw_file, uid, username)
            place_subject = PlaceSubject(username=username
                    ,place_uid=uid
                    ,image=image
                    , thumb=thumb
                    , description=comment)
            place_subject.save()


        try:
            place_comment.save()
            place.comments.append(place_comment)
            if 'photo' in request.FILES:
                place.subjects.append(place_subject)
            place.save()
        except Exception:
            print('failed to store to db')
            print(Exception.args)
            return False
        else:
            return True
